package com.example.spring.security.demo.component;

import com.alibaba.fastjson.JSON;
import com.example.spring.security.demo.entity.ResponseResult;
import com.example.spring.security.demo.utils.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName MyAuthenticationEntryPoint
 * @Description 用户认证失败处理
 * @Author lichuanqi
 * @Date 2022/5/16 14:01
 * @Version 1.0
 **/
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException)
            throws IOException, ServletException {
        System.out.println("######MyAuthenticationEntryPoint#####");
        ResponseResult result = new ResponseResult(HttpStatus.UNAUTHORIZED.value(), "认证失败请重新登录");
        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}
